<?php
/**
 * Created by PhpStorm.
 * User: dragon
 * Date: 2015/11/20
 * Time: 13:57
 */

namespace Wap\Controller;
use Common\Org\Pay\wxpay\lib\WxPayResults;
use Think\Controller;
use Common\Org\Pay\wxpay\lib\WxPayNotifyCallBack;
use Common\Org\Pay\wxpay\unit\CLogFileHandler;
use Common\Org\Pay\wxpay\unit\Log;

class WxPayNotifyController extends Controller
{

    public function index(){
        //初始化日志
        $logHandler= new CLogFileHandler("./wxpaylogs/".date('Y-m-d').'.log');
        Log::Init($logHandler, 15);
        Log::DEBUG("begin notify");

        $notify = new WxPayNotifyCallBack();
        $notify->Handle(false);

        //获取通知的数据
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];

        if($notify->GetReturn_code() == "SUCCESS"){
            $data = WxPayResults::Init($xml);
            $out_trade_no = $data['out_trade_no'];
            $transaction_id = $data['transaction_id'];
            $openid = $data['openid'];
            $total_fee = $data['total_fee'];

            //检测日志同一交易号是否已经完成，已经完成不再执行
            $is_sucess = M('wx_pay_log')->where(array('out_trade_no'=>$out_trade_no,'type'=>1))->getField('status');
            if($is_sucess == 2) return;

            //更新订单状态、数据库操作
            $body = explode(':',$data['attach']);
            $orderno = $body[0];
            $title = $body[1];
            $uid = $body[2];

            $data = array(
                'status'=>2,
                'payway'=>1,
                'paytime'=>time(),
            );
            $map = array();
            $map['uid'] = $uid;
            $map['orderno'] = $orderno;
            $res = M('order')->where($map)->save($data);
            if($res){
                $tips = "【支付成功】";
                $flag = 2;
            }else{
                $tips = "【支付失败】";
                $flag = 1;
            }
        }else{
            $tips = "【支付出错】:".$xml;
            $flag = 1;
        }

        //日志记录
        $total_fee = ($total_fee)/100;
        $log_data = array(
            'out_trade_no'=>$out_trade_no,
            'total_fee'=>$total_fee,
            'body'=>$title,
            'addtime'=>time(),
            'status'=>$flag,
            'remark'=>$tips,
            'type'=>1,
            'transaction_id'=>$transaction_id,
            'openid'=>$openid
        );
        M('wx_pay_log')->add($log_data);
        Log::INFO($tips);
    }

    public function test(){
        $orderno = 'B7050310230204d';
        $title = '罗湖店';
        $uid = 1;

        $data = array(
            'status'=>2,
            'payway'=>1,
            'paytime'=>time(),
        );
        $map = array();
        $map['uid'] = $uid;
        $map['orderno'] = $orderno;
        M('order')->where($map)->save($data);
    }
}